/*引入gulp及相关插件 require('node_modules里对应模块')*/
const gulp = require('gulp')
const minifyCss = require('gulp-minify-css')
const imageMin = require('gulp-imagemin')
const htmlMin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')
const del = require('del')
const babel = require('gulp-babel')
//清理
gulp.task('clean', () => {
  return del(['../dist/*'], {
    force: true
  })
})
gulp.task('copy', () => {
  return gulp.src(['**/*',
    '!.*',
    '!*.*',
    '!**/*.{js,css,html,png,jpg,gif,ico,jpeg}',
    '**/*.min.{js,css}',
    '**/icon-font.js',
    '**/lodash.min.4.17.11.js',
    '!node_modules/**/*',
  ])
    .pipe(gulp.dest('../dist/'))
})
//css压缩
gulp.task('css', () => {
  return gulp.src(['**/*.css',
    '!**/*.min.css',
    '!node_modules/**/*'
  ])
    .pipe(minifyCss())
    .pipe(gulp.dest('../dist/'))
})
//js压缩
gulp.task('js', () => {
  return gulp.src(['**/*.js',
    '!**/*.min.js',
    '!**/icon-font.js',
    '!**/lodash.min.4.17.11.js',
    '!node_modules/**/*',
    '!**/gulpfile.js',
  ])
    .pipe(babel({presets: ['@babel/env']}))
    .pipe(uglify({
      // 混淆变量名
      mangle: true,
      // 输出时将所有的中文转换为unicode
      output: {ascii_only: true}
      // 将所有压缩后的代码置于des/js/文件夹
    }))
    .pipe(gulp.dest('../dist/'))
})
//压缩图片
gulp.task('image', function () {
  return gulp.src(['**/*.{png,jpg,gif,ico,jpeg}',
    '!node_modules/**/*'
  ])
    .pipe(imageMin())
    .pipe(gulp.dest('../dist/'))
})
//添加HASH
gulp.task('html', () => {
  return gulp.src(['**/*.html',
    '!node_modules/**/*'
  ])
    // .pipe(assetRev())//修改资源路径,需要修改gulp-asset-rev源码实现？v=hash的模式
    .pipe(htmlMin({
      removeComments: true, //清除HTML注释
      collapseWhitespace: true, //压缩HTML
      collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input checked />
      removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
      removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
      removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
      minifyJS: true, //压缩页面JS
      minifyCSS: true //压缩页面CSS
    }))
    .pipe(gulp.dest('../dist/'))
})
//删除node_modules
gulp.task('clean_node_modules', () => {
  return del(['../dist/node_modules'], {
    force: true
  })
})
//移动生产配置文件
gulp.task('prod', () => {
  gulp.src('../dist/profiles/prod/*')
    .pipe(gulp.dest('../dist/js/'))
  return del(['../dist/profiles'], {
    force: true
  })
})
gulp.task('default', gulp.series(
  'clean',
  'copy',
  'html',
  gulp.parallel('css', 'js', 'image', (done) => done()),
  'clean_node_modules',
  'prod'
))